package com.redsoil.house.ui.login.presenter;

import com.redsoil.house.app.AppContext;
import com.redsoil.house.base.RxPresenter;
import com.redsoil.house.model.DataManager;
import com.redsoil.house.model.bean.UserVO;
import com.redsoil.house.model.http.exception.ApiException;
import com.redsoil.house.model.http.response.HttpResponse;
import com.redsoil.house.ui.login.contract.LoginContract;
import com.redsoil.house.utils.RxUtil;
import com.redsoil.house.widget.CommonSubscriber;
import com.weidingqiang.rxfiflibrary2.utils.LogUtil;

import javax.inject.Inject;

/**
 * 作者：weidingqiang on 2017/9/7 15:39
 * 邮箱：dqwei@iflytek.com
 */

public class LoginPresenter extends RxPresenter<LoginContract.View> implements LoginContract.Presenter {

    private DataManager mDataManager;

    @Inject
    public LoginPresenter(DataManager mDataManager) {
        this.mDataManager = mDataManager;
    }

    @Override
    public void attachView(LoginContract.View view) {
        super.attachView(view);
        registerEvent();
    }

    private void registerEvent(){

    }

    @Override
    public void login(String loginName, String password) {
        addSubscribe(mDataManager.postLogin(loginName, password)
                        .compose(RxUtil.<HttpResponse<UserVO>>rxSchedulerHelper())
                        .compose(RxUtil.<UserVO>handleTestResult())
                        .subscribeWith(
                                new CommonSubscriber<UserVO>(mView) {
                                    @Override
                                    public void onNext(UserVO userData) {

                                        String Authorization = "Basic "+userData.getToken();

                                          AppContext.getInstance().saveUserInfo(Authorization,userData.getName(),userData.getSex());

                                          mView.loginSuccess(userData);
                                    }


                                    @Override
                                    public void onError(Throwable e) {
                                        //当数据返回为null时 做特殊处理
                                        try {
                                            int code = ((ApiException) e).getCode();
                                            mView.responeError(e.getMessage());
                                            return;
                                        } catch (Exception ex) {

                                        }
                                        mView.responeError("数据请求失败，请检查网络！");
                                    }

                                }
                        )
        );
    }

}
